#include "N76E003.h"
#include "Common.h"
#include "Delay.h"
#include "SFR_Macro.h"
#include "Function_define.h"

#include "xi2cs.h"
#include "xpower.h"
    
//***********************************************************************************************************
//  N76E003-series I2C slave mode, the Slave address = 0xA4
//
//   ____________            _____________
//  |            |   SDA    |             |
//  |            |<-------->|             |---> ADC5(P04) --> Bettery
//  |            |          |             |
//  |(M) AP      |          | N76E003(S)  |---> KEY_TO_AP(P01)  default: 1 
//  |(I2C_Master)|          | (I2C_Slave) |---> POWER_KEY(P00)        input: default: 1
//  |            |   SCL    |             |
//  |            |--------->|             |---> AP_POWER(P12)         default: 0
//  |____________|          |_____________|
//
//***********************************************************************************************************

#define SET_P20UP  (P2S |= SET_BIT7)
#define DE_MASK (0x0F)

void main(void)
{

    UINT8 pkey_debouncing = 0xFF;
    bit pkey_down = 0;
    UINT8 long_press_count = 0;
    UINT8 long_press = 0;

    Set_All_GPIO_Quasi_Mode;
    
    P00_Input_Mode;
    P12_PushPull_Mode;
    P01_PushPull_Mode;
    //demo board
    SET_P20UP;

    P12 = 0;
    P01 = 1;

    /* Initial I2C Slave function */
    init_i2cs();                               

	/* kickoff */
	set_EA;
    
    /* poll power key */   
    while (1) {
        pkey_debouncing = (((pkey_debouncing << 1) | P00) & DE_MASK); //P00;
        if (!pkey_down && (pkey_debouncing == 0)) {
            pkey_down = 1;
         } else if (pkey_down && (pkey_debouncing == DE_MASK)) {
            pkey_down = 0;
            if (!long_press) {
                notify_key_to_ap();            
            } else {
                long_press = 0;
            }
            //power key press release                           
        } else if (pkey_down && (pkey_debouncing == 0)) {
            if (++long_press_count > 25) {
                long_press_count = 0;
                long_press = 1;
                if (!is_ap_powered())
                    set_ap_power_on();
                else
                    set_ap_power_off();
            }
        } else if (pkey_down && (pkey_debouncing !=0 )) {
            long_press_count = 0;
        }
          
        Timer0_Delay1ms(100);
    }
/* =================== */
}
